package edu.vital.energy.longevity.ch10.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import edu.vital.energy.longevity.ch10.domain.Comment;
import edu.vital.energy.longevity.ch10.mapper.CommentMapper;
import edu.vital.energy.longevity.ch10.service.CommentService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.*;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Optional;
import java.util.concurrent.TimeUnit;

// 使用统一的缓存配置
@Service
public class CommentServiceImpl implements CommentService {
    @Autowired
    private CommentMapper commentMapper;

    // ✅ 使用统一缓存键
    @Cacheable(key = "'comment_' + #comment_id")
    @Override
    public Comment findCommentById(int comment_id) {
        return commentMapper.selectById(comment_id);
    }

    // ✅ 使用 Caching 组合更新操作
    @Override
    public List<Comment> insertComment(Comment comment) {
        commentMapper.insert(comment);
        QueryWrapper<Comment> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("a_id", comment.getAId());
        return commentMapper.selectList(queryWrapper);
    }

    @Override
    public List<Comment> updateComment(Comment comment) {
        commentMapper.updateById(comment);
        QueryWrapper<Comment> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("a_id", comment.getAId());
        return commentMapper.selectList(queryWrapper);
    }

    // ✅ 清理所有 comments 缓存
    @Override
    public void deleteComment(int comment_id) {
        commentMapper.deleteById(comment_id);
    }

    // ✅ 按文章ID查询并缓存评论列表
    @Override
    public List<Comment> findCommentsByArticleId(int articleId) {
        QueryWrapper<Comment> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("a_id", articleId);
        return commentMapper.selectList(queryWrapper);
    }

    // ✅ 获取所有评论（不建议频繁调用）
    @Override
    public List<Comment> findAllComments(int articleId) {
        QueryWrapper<Comment> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("a_id", articleId);
        return commentMapper.selectList(queryWrapper);
    }
}